package com.appinfo.controller;

import com.appinfo.annotation.AvoidRepeatableCommit;
import com.appinfo.pojo.AppVersion;
import com.appinfo.pojo.DevUser;
import com.appinfo.service.AppService;
import com.appinfo.service.AppVersionService;
import com.appinfo.vo.AppInfoVo;
import com.appinfo.vo.AppVersionVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/dev/flatform/app")
public class AppVersionController {


    @Autowired
    private AppVersionService appVersionService;
    @Autowired
    private AppService appService;

    /**
     * 前往添加版本信息页面
     * @param devUser
     * @param id
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping("/appversionadd")
    public String toSaveAppVersion(DevUser devUser, @RequestParam(value = "id") Long id, Model model) {
        model.addAttribute("user",devUser);
        List<AppVersionVo> appVersionVos = appVersionService.queryVersionListById(id);  //通过appid查询
        model.addAttribute("appVersionList",appVersionVos);
        model.addAttribute("appId",id);
        return "developer/appversionadd";

    }

    /**
     * 新增版本信息
     * @param devUser
     * @param appVersion
     * @param model
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/addversionsave")
    public String saveAppVersion(DevUser devUser,AppVersion appVersion,Model model,
                                 HttpServletRequest request,MultipartFile file,@RequestParam("appId")Long id) {
        model.addAttribute("user",devUser);
        AppInfoVo appInfoVo = appService.queryAppInfoById(id);

        if(file == null){
            model.addAttribute("fileUploadError","上传失败！");
            model.addAttribute("appid",appInfoVo.getId());
            return "forward:/dev/flatform/app/appversionadd?id="+appInfoVo.getId();
        }
        String oFileName = file.getOriginalFilename();
        String suffixName = oFileName.substring(oFileName.lastIndexOf('.'));
        String prefixName = appInfoVo.getAPKName()+"-"+appVersion.getVersionNo();
        String fileName = suffixName+prefixName;

        long size = file.getSize();
        if(".apk".equals(suffixName) && size < 500*1024*1024){
            //路径
            try {
                String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
                File localFile = new File(path, fileName);
                file.transferTo(localFile);
                //保存下载地址
                String apkPath = "/upload/" + fileName;
                appVersion.setDownloadLink(apkPath);
                appVersion.setApkLocPath(path + fileName);
                appVersion.setApkFileName(fileName);
                appVersionService.saveAppVersion(appVersion, devUser);
                return "redirect:/dev/flatform/app/appversionadd?id=" + appVersion.getAppId();
            }catch (IOException e){
                e.printStackTrace();
                model.addAttribute("fileUploadError","上传失败！");
                return "forward:/dev/flatform/app/appversionadd?id="+appInfoVo.getId();
            }
        } else {
            request.setAttribute("fileUploadError","上传文件格式或大小不正确！");
            return "forward:/dev/flatform/app/appversionadd?id="+appInfoVo.getId();
        }

    }

    /**
     * 前往修改最新版本信息的页面
     * @param devUser
     * @param vid
     * @param aid
     * @param model
     * @return
     */
    @RequestMapping("/appversionmodify")
    public String toUpdateVersion(DevUser devUser,@RequestParam("vid")Long vid,
                                  @RequestParam("aid")Long aid,Model model){
        model.addAttribute("user",devUser);
        List<AppVersionVo> appVersionVos = appVersionService.queryVersionListById(aid);
        model.addAttribute("appVersionList",appVersionVos);
        AppVersion appVersion = appVersionService.queryVersionByVid(vid);
        model.addAttribute("appVersion",appVersion);
        return "developer/appversionmodify";
    }

    /**
     * 修改版本信息
     * @param devUser
     * @param appVersion
     * @return
     */
    @RequestMapping("/appversionmodifysave")
    public String upDateVersion(DevUser devUser,AppVersion appVersion,
                                Model model,MultipartFile file,HttpServletRequest request) {
        model.addAttribute("user",devUser);
        if(file == null){
            model.addAttribute("fileUploadError","上传失败,请重试！");
            return "forward:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()+"&"+"aid="+appVersion.getAppId();
        }
        if(file.isEmpty()){
            appVersionService.updateVersion(appVersion,devUser);
            return "redirect:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()+"&"+"aid="+appVersion.getAppId();
        }else {
            String oFileName = file.getOriginalFilename();
            String suffixName = oFileName.substring(oFileName.lastIndexOf('.'));
            int endIndex = appVersion.getApkFileName().lastIndexOf(".");
            String prefixName = appVersion.getApkFileName().substring(0,endIndex);
            String realName = prefixName + suffixName;
            long size = file.getSize();
            if (".apk".equals(suffixName) && size < 500 * 1024 * 1024) {
                String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
                File localFile = new File(path, realName);
                //捕获上传失败
                try {
                    file.transferTo(localFile);
                    String apkPath = "/upload/" + realName;
                    appVersion.setDownloadLink(apkPath);
                    appVersion.setApkLocPath(localFile + realName);
                    appVersion.setApkFileName(realName);
                    appVersionService.updateVersion(appVersion, devUser);
                    return "redirect:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()+"&"+"aid="+appVersion.getAppId();

                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("fileUploadError", "上传失败！");
                    model.addAttribute("aid",appVersion.getAppId());
                    model.addAttribute("vid",appVersion.getId());
                    return "forward:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()+"&"+"aid="+appVersion.getAppId();
                }

            } else {
                request.setAttribute("fileUploadError", "上传文件格式或大小不正确！");
                return "forward:/dev/flatform/app/appversionmodify?vid="+appVersion.getId()+"&"+"aid="+appVersion.getAppId();
            }
        }



    }
}
